﻿using CommandLib;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using RabbitMQ.Client;
using SignalrChat.Models;
using WeihanLi.Extensions;

namespace SignalrChat.Controllers
{
    public class BaseController : Controller
    {
        //当前登陆帐号
        protected Users users;
        //http请求上下文
        protected IHttpContextAccessor httpContextAccessor;

        public BaseController(IHttpContextAccessor httpContext)
        {
            CookiesHelper.Init(httpContext);    
            httpContextAccessor = httpContext;
        }

        public override void OnActionExecuting(ActionExecutingContext context)
        {

            var rotes = context.ActionDescriptor.RouteValues;
            var actionUrl = $"/{rotes["controller"]}/{rotes["action"]}";
            var cliendData = CookiesHelper.GetCookiesValue(CookiesKey.userLoginKey);
            if (!cliendData.IsEmpty())
            {
                cliendData= DesHelper.DESDecrypt(cliendData);
                users = cliendData.JsonToObject<Users>();
                if (users==null)
                {
                    var rdata = new RtModel<object> { code =401, data = false, message = "用户未登陆！" };

                    context.Result = Json(rdata);
                }
            }
            else
            {
                if (actionUrl=="/Home/Index")
                {
                    Response.Redirect("/Users/login");
                    return;
                }
              
               
            }
            base.OnActionExecuting(context);
        }

        /// <summary>
        /// 跳转到顶层登陆页
        /// </summary>
        /// <param name="httpContext"></param>
        protected async void GoTo(string url)
        {
            await httpContextAccessor.HttpContext.Response.WriteAsync($"<script>top.location.href='{url}'</script>");
        }
    }
}
